package com.rssreader.client.portlets;

import java.util.List;

import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.dnd.DND;
import com.extjs.gxt.ui.client.dnd.DropTarget;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.DNDEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.mvc.Dispatcher;
import com.extjs.gxt.ui.client.widget.TabItem;
import com.extjs.gxt.ui.client.widget.custom.Portlet;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.google.gwt.user.client.Element;
import com.rssreader.client.RSSReaderConstants;
import com.rssreader.client.components.FeedPanel;
import com.rssreader.client.grids.ItemGrid;
import com.rssreader.client.mvc.events.AppEvents;
import com.rssreader.shared.model.Feed;

public class FeedPortlet extends Portlet {
    private final FeedPanel feedPanel = new FeedPanel();

    public FeedPortlet() {
	setHeading("Feed");
	setLayout(new FitLayout());
	setHeight(350);
	setId(RSSReaderConstants.FEED_PORTLET);

	feedPanel.setHeaderVisible(false);
	add(feedPanel);
	Dispatcher.forwardEvent(AppEvents.NewPortletCreated, this);
    }

    @Override
    protected void onRender(Element parent, int pos) {
	super.onRender(parent, pos);
	DropTarget target = new DropTarget(this) {
	    @Override
	    protected void onDragDrop(DNDEvent event) {
		super.onDragDrop(event);
		onFeedsDropped(event);
	    }
	};
	target.setOperation(DND.Operation.COPY);
	target.setGroup(RSSReaderConstants.FEED_DD_GROUP);
    }

    // 擷取DNDEvent data中的BeanModel物件
    private void onFeedsDropped(DNDEvent event) {
	List<BeanModel> beanModels = event.getData();
	for (BeanModel beanModel : beanModels) {
	    Feed feed = beanModel.getBean();
	    final ItemGrid itemGrid = new ItemGrid(feed);
	    TabItem tabItem = new TabItem(feed.getTitle());
	    tabItem.setId(feed.getUuid());
	    tabItem.setData("feed", feed);
	    tabItem.add(itemGrid);
	    tabItem.addListener(Events.Select, new Listener<BaseEvent>() {
		@Override
		public void handleEvent(BaseEvent be) {
		    itemGrid.resetSelection();
		}
	    });
	    tabItem.setClosable(true);
	    feedPanel.addTab(tabItem);
	}
    }

}
